package com.wave.system.thread;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wave.common.utils.DateUtils;
import com.wave.common.utils.StringUtils;
import com.wave.common.utils.redis.RedisUtils;
import com.wave.common.utils.spring.SpringUtils;
import com.wave.system.domain.SysDeviceSetting;
import com.wave.system.domain.SysToolShelfTask;
import com.wave.system.mapper.SysDeviceSettingMapper;
import com.wave.system.mapper.SysToolShelfTaskMapper;
import com.wave.system.util.Modbus4jUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class EmptyShelfArriveListenerThread implements Runnable {


    private final SysDeviceSettingMapper sysDeviceSettingMapper = SpringUtils.getBean(SysDeviceSettingMapper.class);
    private final SysToolShelfTaskMapper sysToolShelfTaskMapper = SpringUtils.getBean(SysToolShelfTaskMapper.class);


    private static final Map<Integer, String> map = new HashMap<>();
    private static final Map<Integer, Integer> map2 = new HashMap<>();

    static {
        map.put(1, "2113");
        map.put(2, "2121");
        map.put(3, "2313");
        map.put(4, "2321");

        //空工装架任务逻辑处理完成后，回复plc处理完成
        map2.put(0, 4112);
        map2.put(1, 4113);
        map2.put(2, 4114);
        map2.put(3, 4115);
    }

    /**
     * A1~A4 PLC送空工装架到达监听线程
     */
    @Override
    public void run() {
        while (true) {
            try {
                boolean[] booleans = Modbus4jUtils.batchReadCoilStatus(1, 4920, 4);

                for (int i = 0; i < booleans.length; i++) {
                    if (booleans[i]) {
                        log.info("监听PLC送空工装架到包装线{}", (i + 1));
                        SysDeviceSetting sysDeviceSetting = sysDeviceSettingMapper.selectOne(Wrappers.emptyWrapper());
                        if (ObjectUtil.isEmpty(sysDeviceSetting)) {
                            log.error("监听PLC送空工装架到包装线异常,无法获取设备设置信息");
                            continue;
                        }
                        String shelfNumber = null;
                        Integer packageLine = null;
                        // 如果第一个RFID读取不到工装架编号，尝试从第二个RFID读写器读取
                        if (i == 0 && StringUtils.isEmpty(RedisUtils.getCacheObject("A1_SHELF"))) {
                            packageLine = 1;
                            String packagingLine1Ip = sysDeviceSetting.getPackagingLine1Ip();
                            //shelfNumber = RFIDReaderWriterUtil.readRFID(packagingLine1Ip);
                            if (StringUtils.isEmpty(shelfNumber)) {
                                String packagingLine1Ip2 = sysDeviceSetting.getPackagingLine1Ip2();
                                //shelfNumber = RFIDReaderWriterUtil.readRFID(packagingLine1Ip2);
                            }
                        }
                        if (i == 1 && StringUtils.isEmpty(RedisUtils.getCacheObject("A2_SHELF"))) {
                            packageLine = 2;
                            String packagingLine2Ip = sysDeviceSetting.getPackagingLine2Ip();
                            //shelfNumber = RFIDReaderWriterUtil.readRFID(packagingLine2Ip);
                            if (StringUtils.isEmpty(shelfNumber)) {
                                String packagingLine2Ip2 = sysDeviceSetting.getPackagingLine2Ip2();
                                //shelfNumber = RFIDReaderWriterUtil.readRFID(packagingLine2Ip2);
                            }
                        }
                        if (i == 2 && StringUtils.isEmpty(RedisUtils.getCacheObject("A3_SHELF"))) {
                            packageLine = 3;
                            String packagingLine3Ip = sysDeviceSetting.getPackagingLine3Ip();
                            //shelfNumber = RFIDReaderWriterUtil.readRFID(packagingLine3Ip);
                            if (StringUtils.isEmpty(shelfNumber)) {
                                String packagingLine3Ip2 = sysDeviceSetting.getPackagingLine3Ip2();
                                //shelfNumber = RFIDReaderWriterUtil.readRFID(packagingLine3Ip2);
                            }
                        }
                        if (i == 3 && StringUtils.isEmpty(RedisUtils.getCacheObject("A4_SHELF"))) {
                            packageLine = 4;
                            String packagingLine4Ip = sysDeviceSetting.getPackagingLine4Ip();
                            //shelfNumber = RFIDReaderWriterUtil.readRFID(packagingLine4Ip);
                            if (StringUtils.isEmpty(shelfNumber)) {
                                String packagingLine4Ip2 = sysDeviceSetting.getPackagingLine4Ip2();
                                //shelfNumber = RFIDReaderWriterUtil.readRFID(packagingLine4Ip2);
                            }
                        }
                        if (packageLine == null) {
                            log.info("A{}包装线已经缓存了工装架编号，直接回复plc处理完成", (i + 1));
                            Modbus4jUtils.writeCoil(1, map2.get(i), true);
                            TimeUnit.MILLISECONDS.sleep(100);
                            continue;
                        }
                        shelfNumber = "DK" + DateUtils.dateTimeNowSSS();
                        //如果最终还是没有从RFID读写器读取到工装架编号，则程序自动生成一个
                       /* if (StringUtils.isEmpty(shelfNumber) || !shelfNumber.startsWith("DK")) {
                            shelfNumber = "DK" + DateUtils.dateTimeNowSSS();
                            log.info("监听PLC送空工装架到包装线RFID读取工装架编码失败，自动生成工装架编号：{}", shelfNumber);
                        }*/
                        log.info("监听PLC送空工装架到{}号包装线,工装架编号：{}", packageLine, shelfNumber);
                        String redisKey = "A" + packageLine + "_SHELF";
                        RedisUtils.setCacheObject(redisKey, shelfNumber);
                        //创建工装架任务
                        SysToolShelfTask sysToolShelfTask = new SysToolShelfTask();
                        sysToolShelfTask.setShelfNumber(shelfNumber);
                        sysToolShelfTask.setTaskStatus("刚创建");
                        String targetExport = map.get(packageLine);
                        sysToolShelfTask.setTargetExport(targetExport);
                        sysToolShelfTask.setRemark("A" + packageLine + "线");
                        sysToolShelfTask.setPackageLine(packageLine);
                        sysToolShelfTaskMapper.insert(sysToolShelfTask);

                        Modbus4jUtils.writeCoil(1, map2.get(i), true);
                    }
                }
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (Exception e) {
                log.error("监听PLC送空工装架到包装线出现未知异常", e);
            }
        }
    }
}
